package edu.clemson.wcbeck.cft;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class CFTFavorites extends ListActivity{

	private MyDatabaseHelper dataSource;
	
	Team mySelectedTeam;
	Toast myToast;
	CharSequence toastText;
	Spinner spnnrFavTeams;
	Button bttnAdd, bttnDelete;
	ListView lstView;
	
	ArrayAdapter<String> spnnrAdapter;
	ArrayAdapter<Team> adapterListView;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.favorites);   
        
        toastText = "Try long pressing on items in the list for more options";
        lstView = (ListView) findViewById(android.R.id.list);
        spnnrFavTeams = (Spinner) findViewById(R.id.spnnrFavTeams);
        bttnAdd = (Button) findViewById(R.id.bttnAddFavorite);
        bttnDelete = (Button) findViewById(R.id.bttnDeleteFavorite);
        
        myToast = Toast.makeText(this.getApplicationContext(), toastText, Toast.LENGTH_LONG);
		myToast.show();
        
        dataSource = new MyDatabaseHelper(this);
        try {
			dataSource.createDataBase();
		} catch (IOException e) {
			toastText = "Error creating the database!";
			myToast = Toast.makeText(this.getApplicationContext(), toastText, Toast.LENGTH_SHORT);
			myToast.show();
			e.printStackTrace();
		}
        
        try {
     		dataSource.openDataBase();
     	}catch(SQLException sqle){
     		toastText = "Error opening the database!";
			myToast = Toast.makeText(this.getApplicationContext(), toastText, Toast.LENGTH_SHORT);
			myToast.show();
     		throw sqle;
     	}
        
        List<Team> values = dataSource.getAllFavTeams();
        adapterListView = new ArrayAdapter<Team>(this, R.layout.list_item, values);
        setListAdapter(adapterListView);
        
        String[] teams = dataSource.getAllTeams();
        
        spnnrAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, teams);
        spnnrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnnrFavTeams.setAdapter(spnnrAdapter);
        
        spnnrFavTeams.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				dataSource.openDataBase();
				mySelectedTeam = dataSource.createTeam(pos+1);
				dataSource.close();
			}

			public void onNothingSelected(AdapterView<?> parent) {
				// Do nothing.
			}
		} );
        
        registerForContextMenu(lstView);
        dataSource.close();
    }
	
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
    	if (v.getId()==android.R.id.list) {
    	    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    	    Team team = (Team) getListAdapter().getItem(info.position);
    	    String[] menuItems = getResources().getStringArray(R.array.strArrContextMenuFavs);
    	    menu.setHeaderTitle(team.getName() + " options:");
    	    
    	    for (int i = 0; i<menuItems.length; i++) {
    	      menu.add(Menu.NONE, i, i, menuItems[i]);
    	    }
    	  }
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
      int menuItemIndex = item.getItemId();
      dataSource.openDataBase();
      
      @SuppressWarnings("unchecked")
      ArrayAdapter<Team> adapter = (ArrayAdapter<Team>) getListAdapter();
	  Team team = (Team) getListAdapter().getItem(info.position);
	  
      switch(menuItemIndex){
      case 0: //Edit
    	  break;
      case 1: //Delete
    	  dataSource.deleteTeam(team);
    	  adapter.remove(team);
    	  break;
      case 2: //Set
    	  break;
      }
      
      dataSource.close();
      return true;
    }
    
	// Will be called via the onClick attribute
	// of the buttons in main.xml
	public void onClick(View view) {
		dataSource.openDataBase();
		
		@SuppressWarnings("unchecked")
		ArrayAdapter<Team> adapter = (ArrayAdapter<Team>) getListAdapter();
		Team team = null;
		switch (view.getId()) {
		case R.id.bttnAddFavorite:
			if(!(dataSource.insertTeam(mySelectedTeam))) { adapter.add(mySelectedTeam); }
			break;
		case R.id.bttnDeleteFavorite:
			
			
			ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
			String result = "";  
			try{
	              HttpClient httpclient = new DefaultHttpClient();
	              HttpPost httppost = new HttpPost("http://pba.cs.clemson.edu/~wcbeck/webservice.php");
	              HttpResponse response = httpclient.execute(httppost);
	              HttpEntity entity = response.getEntity();
	              InputStream is = entity.getContent();

	              BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	              StringBuilder sb = new StringBuilder();
	              String line = null;
	              while ((line = reader.readLine()) != null) {
	                      sb.append(line + "\n");
	              }
	              is.close();
	       
	              result=sb.toString();
	              
	              JSONArray jArray = new JSONArray(result);
	              for(int i=0;i<jArray.length();i++){
	            	  HashMap<String, String> map = new HashMap<String, String>();
	                      JSONObject json_data = jArray.getJSONObject(i);
	                      map.put("_id", ((Integer)json_data.getInt("_id")).toString());
	                      map.put("conf_id", json_data.getString("conf_id"));
	                      map.put("name", json_data.getString("name"));
	                      //map.put("full_name", json_data.getString("full_name"));
	                      mylist.add(map);
	              }
	      }catch(Exception e){
	              Log.e("log_tag", "Error parsing data "+e.toString());
	      }

			ListAdapter adpt = new SimpleAdapter(this, mylist, R.layout.list_item, new String[] {"_id", "conf_id", "name", "full_name"}, null);
			
			lstView.setAdapter(adpt);
			

			
//			
//			if (getListAdapter().getCount() > 0) {
//				team = (Team) getListAdapter().getItem(0);
//				dataSource.deleteTeam(team);
//				adapter.remove(team);
//			}
			break;
		}
		adapter.notifyDataSetChanged();
		dataSource.close();
	}
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.aboutmenu, menu);
        return true;
    }
    
    public void initMain(){
    	Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }
    
    /*public void initExit(){
    	Intent intent = new Intent(this, FinActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	startActivity(intent);
    	finish();
    }*/
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.icFavorites: //initAbout();
                                break;
            case R.id.icBack: initMain();
            					break;
            //case R.id.icExit: initExit();
            //					break;
        }
        return true;
    }
	
}
